package com.itfreer.arcgis.gps;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import com.esri.arcgisruntime.mapping.view.MapView;

/**
 * 螺旋，方向
 */
public class GPSSensorListener implements SensorEventListener {

    private ImageView compassImage = null;
    private Sensor mSensor;

    // 记录指南针图片转过的角度
    float currentDegree = 0f;

    public SensorManager getSensorManager() {
        return sensorManager;
    }

    public void setSensorManager(SensorManager sensorManager) {
        this.sensorManager = sensorManager;
    }

    public SensorManager sensorManager = null;

    public MapView getMapView() {
        return mapView;
    }

    public void setMapView(MapView mapView) {
        this.mapView = mapView;
    }

    private MapView mapView;

    /**
     * 初始化
     *
     * @param mapView
     * @param mapView
     */
    public void Init(MapView mapView) {
        this.mapView = mapView;
        // 获取界面中显示指南针的图片
        Activity activity = (Activity) mapView.getContext();
//        activity.findViewById(R.id.centerDirection).setVisibility(View.VISIBLE);
//        compassImage = (ImageView) activity.findViewById(R.id.centerDirectionImage);
        // 获取传感器管理服务
        sensorManager = (SensorManager) activity.getSystemService(activity.SENSOR_SERVICE);
        // 获得方向传感器
        mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    }

    public void Close() {
//        Activity activity = (Activity) mapView.getContext();
//        activity.findViewById(R.id.centerDirection).setVisibility(View.GONE);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        // 获取触发event的传感器类型
        int sensorType = sensorEvent.sensor.getType();
        if (sensorType == Sensor.TYPE_ORIENTATION) {
            // 获取绕Z轴转过的角度
            float degree = sensorEvent.values[0];
            // 创建旋转动画（反向转过degree度）
            RotateAnimation ra = new RotateAnimation(currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            // 设置动画的持续时间
            ra.setDuration(200);
            // 运行动画
            compassImage.startAnimation(ra);
            currentDegree = -degree;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
    }
}